<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="预约时间" prop="createTime">
        <el-date-picker
          clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约时间"
          style="width: 150px"
        >
        </el-date-picker>
      </el-form-item> -->

      <el-form-item label="预约开始时间" prop="startDate" label-width="100px">
        <el-date-picker
          clearable
          v-model="queryParams.startDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约结束时间" prop="endDate" label-width="100px">
        <el-date-picker
          clearable
          v-model="queryParams.endDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间"
          :end-placeholder="parseTime(new Date(), '{y}-{m}-{d}')"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="补发师名字" prop="teacherName" label-width="82px">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入补发师名字"
          clearable
          @keyup.enter="handleQuery"
          class="hair-id"
        />
      </el-form-item>
      <el-form-item
        label="核销老师昵称"
        prop="finishTeacherName"
        label-width="100px"
      >
        <el-input
          v-model="queryParams.finishTeacherName"
          placeholder="请输入核销老师昵称"
          clearable
          @keyup.enter="handleQuery"
          class="user-id"
        />
      </el-form-item>
      <el-form-item label="门店名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入门店名称"
          clearable
          @keyup.enter="handleQuery"
          class="shop-id"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter="handleQuery"
          class="user-id"
        />
      </el-form-item>
      <el-form-item label="销售昵称" prop="inviterName">
        <el-input
          v-model="queryParams.inviterName"
          placeholder="请输入销售昵称"
          clearable
          @keyup.enter="handleQuery"
          class="user-id"
        />
      </el-form-item>

      <el-form-item label="预约状态" prop="status">
        <el-select
          @change="handleQuery"
          v-model="queryParams.status"
          placeholder="预约状态"
          clearable
          style="width: 100px"
        >
          <el-option
            v-for="dict in sys_subscribe_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约类型" prop="subscribeType">
        <el-input
          v-model="queryParams.subscribeType"
          placeholder="请输入预约类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="到店开始日期"
        prop="reachStartDate"
        label-width="100px"
      >
        <el-date-picker
          clearable
          v-model="queryParams.reachStartDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约日期"
          style="width: 150px"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="到店结束日期"
        prop="reachendDate"
        label-width="100px"
      >
        <el-date-picker
          clearable
          v-model="queryParams.reachendDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约日期"
          style="width: 150px"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:hairTeacherSubscribe:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:hairTeacherSubscribe:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="hairTeacherSubscribeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="预约时间" align="center" prop="createTime">
        <template #default="scope">
          <div>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</div>
          <div>{{ parseTime(scope.row.createTime, "{h}:{i}:{s}") }}</div>
        </template>
      </el-table-column>

      <el-table-column label="补发师" align="center" prop="teacherId">
        <template #default="scope">
          <div>
            {{ scope.row.teacherName }}
          </div>
        </template>
      </el-table-column>
<!--      <el-table-column label="核销老师" align="center" prop="nickName">-->
<!--        <template #default="scope">-->
<!--          <div v-if="scope.row.geekFinishTeacher">-->
<!--            {{ scope.row.geekFinishTeacher.nickName }}-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="门店名称" align="center" prop="shopId">
        <template #default="scope">
          <div>
            {{ scope.row.shopName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userId">
        <template #default="scope">
          <div>
            {{ scope.row.userName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户手机号" align="center" prop="phonenumber">
        <template #default="scope">
          <div>
            {{ scope.row.phonenumber }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="销售昵称" align="center" prop="inviterId">
        <template #default="scope">
          <div>
            {{ scope.row.inviterName }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="待预约昵称" align="center" prop="inviterId">
        <template #default="scope">
          <div>
            <div>
              {{ scope.row.replaceNickName }}
            </div>
            <div>
              <el-tag
                v-if="scope.row.isReplace == 1"
                type="primary"
                style="margin-left: 10px"
              >
                代
              </el-tag>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="所属主管"
        align="center"
        prop="salesExecutiveName"
      />
      <el-table-column label="预约类型" align="center" prop="subscribeType" />
      <!-- <el-table-column
        label="预约码"
        align="center"
        prop="code"
        style="display: none"
      >
        <template #default="scope">
          <template v-if="scope.row.code != null">
            <template v-for="item in scope.row.code.split(',')" :key="item">
              <image-preview :src="item" :width="50" :height="50" />
            </template>
          </template>
        </template>
      </el-table-column> -->

      <el-table-column label="到店日期" align="center" prop="subscribeTime">
        <template #default="scope">
          <div>{{ parseTime(scope.row.subscribeDate, "{y}-{m}-{d}") }}</div>
          <div>{{ scope.row.timePeriod }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="预约日期"
        align="center"
        prop="subscribeDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.subscribeDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="预约星期" align="center" prop="subscribeDay" /> -->
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <div v-if="scope.row.signTime">
            <dict-tag :options="sys_subscribe_status" :value="10" />
          </div>
          <div v-else>
            <dict-tag :options="sys_subscribe_status" :value="scope.row.status" />
          </div>

        </template>
      </el-table-column>

      <el-table-column label="取消原因" align="center" prop="cancelReason" />
      <el-table-column
        label="核销时间"
        align="center"
        prop="finishTime"
        width="100"
      >
        <template #default="scope">
          <div>{{ parseTime(scope.row.finishTime, "{y}-{m}-{d}") }}</div>
          <div>{{ parseTime(scope.row.finishTime, "{h}:{i}:{s}") }}</div>
        </template>
      </el-table-column>

      <!-- 新增字段 -->
      <el-table-column
        label="签单时间"
        align="center"
        prop="signTime"
        width="100"
      >
        <template #default="scope">
          <div>{{ parseTime(scope.row.signTime, "{y}-{m}-{d}") }}</div>
          <div>{{ parseTime(scope.row.signTime, "{h}:{i}:{s}") }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="签单老师"
        align="center"
        prop="signTeacherName"
        width="100"
      />
      <el-table-column
        label="签单价格"
        align="center"
        prop="signPrice"
        width="100"
      />
      <el-table-column
        label="签单项目"
        align="center"
        prop="signProject"
        width="100"
      />
      <!-- 新增字段end -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改补发师预约对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="hairTeacherSubscribeRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="代约人">
          <el-input
            v-model="people"
            maxlength="30"
            disabled
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="补发师名字" prop="teacherId">
          <el-select
            v-model="form.teacherId"
            filterable
            remote
            placeholder="请输入补发师名字"
            :remote-method="remoteMethod"
            :loading="loading"
            style="width: 240px"
            @change="onChange"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="补发师名字" prop="teacherId">
          <el-select
            v-model="form.teacherId"
            placeholder="请选择补发师名字"
            style="width: 240px"
          >
            <el-option
              v-for="item in teacherList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="用户手机" prop="phonenumber">
          <el-input
            v-model="form.phonenumber"
            maxlength="30"
            placeholder="请输入用户手机"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="预约类型" prop="subscribeType">
          <el-select
            v-model="form.subscribeType"
            placeholder="请选择预约类型"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in booked_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="预约日期" prop="subscribeDate">
          <el-date-picker
            clearable
            v-model="form.subscribeDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预约时间"
            style="width: 240px"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="预约时间" prop="timePeriod">
          <el-select
            v-model="form.timePeriod"
            placeholder="请选择预约时间"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in booked_time"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HairTeacherSubscribe">
import {
  listHairTeacherSubscribe,
  getHairTeacherSubscribe,
  delHairTeacherSubscribe,
  addHairTeacherSubscribe,
  updateHairTeacherSubscribe,
} from "@/api/business/hairTeacherSubscribe";
import { listHairFixTeacher } from "@/api/business/hairFixTeacher";
import cache from "@/plugins/cache";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();

const { proxy } = getCurrentInstance();
const { sys_subscribe_status, sys_normal_disable, booked_type, booked_time } =
  proxy.useDict(
    "sys_subscribe_status",
    "sys_normal_disable",
    "booked_type",
    "booked_time"
  );
const hairTeacherSubscribeList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    replaceUserId: userStore.$state.id,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    teacherId: undefined,
    shopId: undefined,
    userId: undefined,
    subscribeType: undefined,
    code: undefined,
    status: undefined,
    teacherInfo: undefined,
    shopInfo: undefined,
    timePeriod: undefined,
    subscribeDate: undefined,
    subscribeDay: undefined,
    finishTime: undefined,
    teacherName: undefined,
    finishTeacherName: undefined,
    shopName: undefined,
    userName: undefined,
    inviterName: undefined,
    startDate: undefined,
    endData: undefined,
    reachStartDate: undefined,
    reachendDate: undefined,
  },
  rules: {
    phonenumber: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
    ],
    id: [{ required: true, message: "不能为空", trigger: "blur" }],
    teacherId: [
      { required: true, message: "补发师id不能为空", trigger: "blur" },
    ],
    shopId: [{ required: true, message: "门店id不能为空", trigger: "blur" }],
    userId: [{ required: true, message: "用户id不能为空", trigger: "blur" }],
    subscribeType: [
      { required: true, message: "预约类型不能为空", trigger: "change" },
    ],
    code: [{ required: true, message: "预约码不能为空", trigger: "blur" }],
    status: [
      { required: true, message: "预约状态不能为空", trigger: "change" },
    ],
    teacherInfo: [
      {
        required: true,
        message: "补发师详情,json存储不能为空",
        trigger: "blur",
      },
    ],
    shopInfo: [
      { required: true, message: "门店详情,json存储不能为空", trigger: "blur" },
    ],
    timePeriod: [
      { required: true, message: "预约时间段不能为空", trigger: "blur" },
    ],

    subscribeDate: [
      { required: true, message: "预约日期不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
const teacherList = ref([]);

const people = ref(undefined);
onMounted(() => {
  // const sessionObj = JSON.parse(
  //   cache.session.getJSON("sessionObj").data
  // ).username;
  // console.log(sessionObj);
  //
  // people.value = sessionObj;
  // console.log("people.value=>", people.value);
  people.value = userStore.name;
});

const value = ref([]);
/** 查询补发师信息列表 */
function getTeacherList() {
  // console.log(queryParams.value);
  loading.value = true;
  listHairFixTeacher({
    pageNum: 1,
    pageSize: 10000,
  }).then((response) => {
    // teacherList.value = response.rows;
    // console.log(response.rows);
    teacherList.value = response.rows.map((item) => {
      return {
        key: `${item.id}`,
        value: `${item.id}`,
        label: `${item.nickName}`,
        phonenumber: `${item.phonenumber}`,
      };
    });
  });
}

// 远程搜索方法
const options = ref([]);
const remoteMethod = (query) => {
  // console.log(query, "00000000000000");

  // rerurn;
  if (query) {
    // loading.value = true;
    setTimeout(() => {
      // loading.value = false;
      options.value = teacherList.value.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    }, 200);
  } else {
    options.value = [];
  }
};

function onChange() {
  // console.log(999);
}

/** 查询补发师预约列表 */
function getList() {
  loading.value = true;
  // console.log(queryParams.value);
  listHairTeacherSubscribe(queryParams.value).then((response) => {
    hairTeacherSubscribeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    teacherId: null,
    shopId: null,
    userId: null,
    subscribeType: null,
    code: null,
    status: null,
    teacherInfo: null,
    shopInfo: null,
    timePeriod: null,
    subscribeDate: null,
    subscribeDay: null,
    finishTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    delFlag: null,
    teacherName: undefined,
    finishTeacherName: undefined,
    shopName: undefined,
    userName: undefined,
    inviterName: undefined,
    reachStartDate: undefined,
    reachendDate: undefined,
  };
  proxy.resetForm("hairTeacherSubscribeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户预约信息-代预约";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true;
  reset();
  const _id = row.id || ids.value;
  getHairTeacherSubscribe(_id).then((response) => {
    loading.value = false;
    form.value = response.data;
    form.value.status = response.data.status.toString();
    open.value = true;
    title.value = "修改补发师预约";
  });
}

/** 提交按钮 */
function submitForm() {
  console.log(form.value);
  // return;
  proxy.$refs["hairTeacherSubscribeRef"].validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateHairTeacherSubscribe(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        form.value.replaceUserId = userStore.$state.id;
        form.value.replaceNickName = people.value;
        console.log(form.value);
        // return;
        addHairTeacherSubscribe(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除补发师预约编号为"' + _ids + '"的数据项？')
    .then(function () {
      loading.value = true;
      return delHairTeacherSubscribe(_ids);
    })
    .then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "business/hairTeacherSubscribe/export",
    {
      ...queryParams.value,
    },
    `hairTeacherSubscribe_${new Date().getTime()}.xlsx`
  );
}

getList();
getTeacherList();
</script>

<style lang="scss" scoped>
.hair-id {
  width: 134px;
}
.shop-id {
  width: 124px;
}
.user-id {
  width: 124px;
}
</style>
